package com.ruoyi.web.controller.task;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

public class ServiceVps {


    public static void main(String[] args) {
        System.out.println(JSON.toJSONString(query_aweme_relation_listV("52f1fb0ad10c96fff1059642c7a2b37c","tte9ee9f5376df784901")));
    }

    public static JSONArray query_aweme_relation_listV(String ticket, String appId) {
        //获取前置的token
        String component_access_token = getComponent_access_token(ticket);

        //找回授权码
        String authorization_code = findBackRetrieve(component_access_token, appId);

        String authorizer_access_token = getAuthorizer_access_token(component_access_token, authorization_code);
         return  query_aweme_relation_list(authorizer_access_token);
    }

    /**
     * @desc 查询抖音号绑定列表及状态
     * @author gq
     * @date 2024-03-02 10:55
     */
    public static JSONArray query_aweme_relation_list(String accessToken){
        try {
            // 获取到了code值，回调没有问题
            // 定义地址
            Map<String,String> param = new HashMap<>();
            StringBuilder stringBuilder = new StringBuilder("https://open.douyin.com/api/apps/v1/capacity/query_aweme_relation_list/");
            stringBuilder.append("?type=employee");
            stringBuilder.append("&page_num=1");
            stringBuilder.append("&page_size=50");
            CloseableHttpClient httpClient = HttpClients.createDefault();
            //设置超时时间
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000).setConnectionRequestTimeout(1000).setSocketTimeout(5000).build();
            HttpGet httpget = new HttpGet(stringBuilder.toString());
            httpget.addHeader("access-token", accessToken);
            httpget.addHeader("Content-Type", "application/json");
            httpget.setConfig(requestConfig);
            CloseableHttpResponse response = httpClient.execute(httpget);
            HttpEntity entity = response.getEntity();
            String responseContent = EntityUtils.toString(entity, "UTF-8");
            System.out.println(responseContent);
            JSONObject jsonObject = JSON.parseObject(responseContent);
            JSONArray jsonArray = jsonObject.getJSONObject("data").getJSONArray("list");

            for(int n =0; n < jsonArray.size(); n++ ){
//                抖音号类型1：企业号2：个人号
                System.out.println(jsonArray.getJSONObject(n).getInteger("account_type"));
//                绑定状态251：绑定失败281：审核拒绝291：审核中301：待C端同意302：绑定成功
                System.out.println(jsonArray.getJSONObject(n).getInteger("bind_status"));

                System.out.println(jsonArray.getJSONObject(n).getString("aweme_id"));
                System.out.println(jsonArray.getJSONObject(n).getString("user_name"));
            }
            System.out.println("jsonObject:" + JSON.toJSONString(jsonObject));
            response.close();
            httpClient.close();
             return  jsonArray;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * @desc 找回授权码
     * @author gq
     * @date 2024-03-02 10:57
     */
    public static String findBackRetrieve(String component_access_token, String appId){
        try {
            Map<String,String> param = new HashMap<>();
            // 获取到了code值，回调没有问题
            StringBuilder stringBuilder = new StringBuilder("https://open.douyin.com/api/tpapp/v2/auth/retrieve_auth_code/");
           /* stringBuilder.append("?component_appid=tt6a241c99f50ec1b5");
            stringBuilder.append("&component_access_token=" + component_access_token);
            stringBuilder.append("&authorization_appid=" + appId);*/

            param.put("authorization_appid",appId );

            CloseableHttpClient httpClient = HttpClients.createDefault();
            //设置超时时间
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000).setConnectionRequestTimeout(1000).setSocketTimeout(5000).build();
            HttpPost httpPost = new HttpPost(stringBuilder.toString());
            httpPost.setConfig(requestConfig);
            httpPost.addHeader("access-token", component_access_token);

            httpPost.addHeader("Content-Type", "application/json");
            httpPost.setEntity(new StringEntity(JSON.toJSONString(param)));
            CloseableHttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            String responseContent = EntityUtils.toString(entity, "UTF-8");
            JSONObject jsonObject = JSON.parseObject(responseContent);
            System.out.println("jsonObject:" + JSON.toJSONString(jsonObject));
//            :{"authorization_code":"li9J8_1brTm822i3YwnR0ozq1ELa0FweLWNd3ZU1s6Lndbpy","expires_in":3600}
            response.close();
            httpClient.close();
            return jsonObject.getJSONObject("data").getString("authorization_code");
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    public static String getComponent_access_token(String ticket){
        try {
            // 获取到了code值，回调没有问题
            // 定义地址
            StringBuilder stringBuilder = new StringBuilder("https://open.douyin.com/openapi/v2/auth/tp/token/");
            stringBuilder.append("?component_appid=tt6a241c99f50ec1b5");
            stringBuilder.append("&component_appsecret=5eacbee6bb9f5a37d7286b0a130cebd13ca89c5d");
//            stringBuilder.append("?component_appid=tte9ee9f5376df784901");
//            stringBuilder.append("&component_appsecret=920c026ecb6c9c318b4ca7645fc95036db584bee");
            stringBuilder.append("&component_ticket=" + ticket);
            CloseableHttpClient httpClient = HttpClients.createDefault();
            //设置超时时间
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000).setConnectionRequestTimeout(1000).setSocketTimeout(5000).build();
            HttpGet httpPost = new HttpGet(stringBuilder.toString());
            httpPost.setConfig(requestConfig);
            CloseableHttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            String responseContent = EntityUtils.toString(entity, "UTF-8");
            JSONObject jsonObject = JSON.parseObject(responseContent);
            System.out.println("jsonObject:" + JSON.toJSONString(jsonObject));
            response.close();
            httpClient.close();
            return jsonObject.getString("component_access_token");
//            41be57694fb489c9977d3583120190bb4e5d3bb865291bab75fe7ed99cf68f98949e409f708618d9ff211d99cd7399cd415cda6fa778e5fe409111540d7c4e8ae6971b9e92a46e84e2048ac9e6a53
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }catch (IOException e) {
            e.printStackTrace();
        }
        return null;

    }

    public static String getAuthorizer_access_token(String component_access_token, String authorization_code){
        try {
            // 获取到了code值，回调没有问题
            // 定义地址
            Map<String,String> param = new HashMap<>();
            StringBuilder stringBuilder = new StringBuilder("https://open.douyin.com/api/tpapp/v2/auth/get_auth_token/");
//            StringBuilder stringBuilder = new StringBuilder("https://open.microapp.bytedance.com/openapi/v1/oauth/token");
//            stringBuilder.append("?component_appid=tt6a241c99f50ec1b5");
//            stringBuilder.append("&component_access_token=" + component_access_token);

            stringBuilder.append("?grant_type=app_to_tp_authorization_code");
            stringBuilder.append("&authorization_code=" + authorization_code);
            CloseableHttpClient httpClient = HttpClients.createDefault();
            //设置超时时间
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000).setConnectionRequestTimeout(1000).setSocketTimeout(5000).build();
//           正式 https://developer.toutiao.com/api/apps/v2/token
//            测试 https://open-sandbox.douyin.com/api/apps/v2/token
            HttpGet httpPost = new HttpGet(stringBuilder.toString());
            httpPost.setConfig(requestConfig);
            httpPost.addHeader("access-token", component_access_token);
//            httpPost.setEntity(new StringEntity(JSON.toJSONString(param)));
            CloseableHttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            String responseContent = EntityUtils.toString(entity, "UTF-8");
            JSONObject jsonObject = JSON.parseObject(responseContent);
            System.out.println("jsonObject:" + JSON.toJSONString(jsonObject));
            response.close();
            httpClient.close();


//            jsonObject:{"authorizer_access_token":"08021218463765623567534a3837503659684b6433487a5546673d3d","expires_in":7200,"authorizer_refresh_token":"be6e1be0980e3a6588cfc582720b37a858baa36a545f8fba8d7a3bcf5bf250c36d1298d007f83ae34786460f88b30ee140e7c32a3e0c92aed0b54fa6a7b78d0432f09b13bb890a441d09aded2e1fe","refresh_expires_in":2592000,"authorizer_appid":"ttb562c3df2a520f7301","authorize_permission":[{"id":1,"category":"开发管理权限","description":"帮助小程序进行基础功能开发及配置开发所需信息"},{"id":2,"category":"基本信息设置权限","description":"帮助小程序管理名称、头像、简介、服务类目等信息"},{"id":3,"category":"运营管理权限","description":"帮助小程序接入平台提供的开放能力，包括自主挂载、达人推广、搜索等"},{"id":4,"category":"数据分析权限","description":"能够获得小程序相关数据并进行数据分析，主要包括小程序用户数据及交易数据"},{"id":5,"category":"广告管理权限","description":"帮助小程序进行广告投放及管理"},{"id":6,"category":"支付服务权限","description":"帮助小程序开通及使用支付产品，并获得支付产生的相关数据"},{"id":7,"category":"流量主权限","description":"帮助开发者管理小程序内的广告变现业务"},{"id":8,"category":"小程序推广计划-任务管理权限","description":"帮助开发者发布小程序推广任务并查看任务相关信息"}],"share_data":{"share_ratio":0,"share_amount":0}}
            return jsonObject.getJSONObject("data").getString("authorizer_access_token");
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }catch (IOException e) {
            e.printStackTrace();
        }
        return null;

    }





}
